package com.ypx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ypx.bean.Category;
import com.ypx.bean.Dish;
import com.ypx.common.R;
import com.ypx.dto.DishDto;
import com.ypx.service.CategoryService;
import com.ypx.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/dish")
@Api(tags = "菜品")
@RestController
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> addDish(@RequestBody DishDto dishDto) {
        //1.调用service的新增方法
        dishService.addDishWithFlavors(dishDto);

//        //优化：清理全部缓存
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        //优化：清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        //2.返回结果
        return R.success("新增成功！");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(@RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "10") Integer pageSize, String name) {

        //设置查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Dish::getName, name);
        wrapper.orderByDesc(Dish::getUpdateTime);

        //0.添加分页拦截器
        //1.设置分页对象 Page对象
        Page<Dish> dishPage = new Page<>(page, pageSize);

        //优化：
        //1.创建一个新的page对象Page<DishDto>
        Page<DishDto> dishDtoPage = new Page<>();

        //3.调用service的分页查询方法
        dishService.page(dishPage, wrapper);
//        Page<Dish> dishPage = dishService.page(new Page<>(page, pageSize), wrapper);

        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        //3.设置Page<DishDto>的records属性，构造List<DishDto>数据
        List<DishDto> dishDtoList = new ArrayList<>();

        //3.1 循环遍历List<Dish>，
        List<Dish> dishList = dishPage.getRecords();
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            //将dish数据复制给dishDto
            BeanUtils.copyProperties(dish, dishDto);  //dish: aa=11 bb==22,, dishDto: aa=11  cc=null
            //3.2 查询出category，将分类名称赋值给dishDto
            Category category = categoryService.getById(dish.getCategoryId());
            dishDto.setCategoryName(category.getName());

            //3.3 将dishDto添加到List<DishDto>
            dishDtoList.add(dishDto);
        }

//        //对象拷贝 .stream().map((item)的方式
//        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
//        List<Dish> records = pageInfo.getRecords();
//        List<DishDto> list = records.stream().map((item) -> {
//
//            DishDto dishDto = new DishDto();
//            BeanUtils.copyProperties(item,dishDto);
//            Long categoryId = item.getCategoryId();//分类id
//            //根据id查询分类对象
//            Category category = categoryService.getById(categoryId);
//
//            if(category != null){
//                String categoryName = category.getName();
//                dishDto.setCategoryName(categoryName);
//            }
//            return dishDto;
//        }).collect(Collectors.toList());
//        dishDtoPage.setRecords(list);

        //4.设置Page<DishDto>的records属性
        dishDtoPage.setRecords(dishDtoList);

        //5.返回结果
        return R.success(dishDtoPage);
    }

    /**
     * 查询菜品信息包含口味信息，（回显原本的口味）
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getDish(@PathVariable Long id) {
        //1.调用service的查询方法
        DishDto dishDto = dishService.getDishWithFlavors(id);
        //2.返回结果
        return R.success(dishDto);
    }

    /**
     * 修改菜品包含口味信息修改
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        //1.调用service的修改方法
        dishService.updateWithFlavors(dishDto);

//        //优化：清理全部缓存
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        //优化：清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        //2.返回结果
        return R.success("修改成功！");
    }

    /**
     * 查询菜品列表包含口味信息，（下拉框）
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtos = null;
        //构造redis的key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        //优化：先从redis中查询是否存在缓存数据
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtos != null){
            return R.success(dishDtos);
        }

        //1.调用service的查询方法
        dishDtos = dishService.listWithFlavors(dish);

        //优化：添加到Redis缓存中
        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);

        //2.返回结果
        return R.success(dishDtos);
    }

    /**
     * 删除分类
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        //1.调用service层的删除
        dishService.deleteWithDish(ids);
        //2.返回结果
        return R.success("删除成功！");
    }

    @PostMapping("/status/{id}")
    public R<String> updateStatus(@PathVariable("id") Long id, @RequestParam("ids") List<Long> ids){
        //1.判断id是0还是1，（0代表停售，1代表启售）
        dishService.updateStatusById(id,ids);
        if (id==0){
            return R.success("停售成功！");
        }else {
            return R.success("启售成功！");
        }
    }
}
